class_name Player
extends CharacterBody2D

var move_vector := Vector2.ZERO
@export var move_accel: float = 1800
@export var move_maximum: float = 360  # maximum speed
@export var sway_scale: float = 1800

@export_category("Scene Resources")
@export var bullet_scene: PackedScene  # must select a scene for bullet
@export var ui_layers: Array[PackedScene] = []

@onready var sprite_2d: Sprite2D = $Sprite2D
@onready var canvas_layer: CanvasLayer = $CanvasLayer
@onready var animation_player: AnimationPlayer = $AnimationPlayer
@onready var attack_cool_timer: Timer = $AttackCoolTimer  # 攻击冷却计时器


func _ready() -> void:
	# Load ui elements
	for layer in ui_layers:
		var node := layer.instantiate()
		canvas_layer.add_child(node)

func _physics_process(delta: float) -> void:
	# 接受左右移动事件
	move_vector.x = Input.get_action_strength("move_right") - Input.get_action_strength("move_left")
	velocity.x += delta * move_vector.x * move_accel
	velocity.x = clamp(velocity.x, -move_maximum, move_maximum)
	
	if move_vector.x == 0:
		velocity.x = lerp(0.0, velocity.x, pow(2, -5 * delta))  # 缓慢减速
	
	var tmp := position + Vector2(velocity.x, -sway_scale)
	sprite_2d.rotation = position.angle_to_point(tmp) + PI / 2

	move_and_slide()


func _process(delta: float) -> void:
	if animation_player.current_animation == "attack" and !animation_player.is_playing():
		animation_player.play("idle")


func has_attack() -> bool:
	return attack_cool_timer.is_stopped()


func attack() -> void:
	animation_player.play("attack")
	attack_cool_timer.start()
